<?php
namespace DB;

use DBConnection\DBConnection;
class User
{
	public function test()
	{
		echo 'test User' . '</br>';
	}
	public function getAllUsers()
	{
		$connection = DBConnection::getDBConnection();
		$sql = "select *\n"
				. " from user";
		$stmt = $connection->prepare($sql);
		$stmt->execute();
		while ($row = $stmt->fetch())
		{
			echo '<p>';
			echo $row['user_id'] . " " . $row['name'] . " " . $row['age'];
			echo '</p>';
		}
	}
	public function findUser($name)
	{
		$connection = DBConnection::getDBConnection();
		$sql = "select *\n"
				. " from user\n"
				. " where `name` like :NAME";
		$stmt = $connection->prepare($sql);
		$stmt->bindValue(":NAME", $name, \PDO::PARAM_STR);
		$stmt->execute();
		echo 'ID-NAME-AGE';
		while ($row = $stmt->fetch())
		{
			echo '<p>';
			echo $row['user_id'] . " " . $row['name'] . " " . $row['age'];
			echo '</p>';
		}
	}
	public function insertUser($name, $age)
	{
		if(strlen($name) == 0)
		{
			throw new \Exception("No Name Inputed!");
		}
		settype($name, "string");
		settype($age, "int");
		if(!is_string($name))
		{
			throw new \Exception("String Needed!");
		}
		if(strlen($name) > 10)
		{
			throw new \Exception("Name to long!");
		}
		if(!is_int($age) || $age <= 0 || $age >= 100)
		{
			throw new \Exception("Age must be a natural number, greater than 0 and less than 100 !");
		}
		$connection = DBConnection::getDBConnection();
		$sql = "INSERT INTO `user`(`name`, `age`) 
				VALUES ( :NAME, :AGE)";
		$stmt = $connection->prepare($sql);
		$stmt->bindValue(":NAME", $name, \PDO::PARAM_STR);
		$stmt->bindValue(":AGE", $age, \PDO::PARAM_INT);
		$stmt->execute();
	}
	public function deleteUser($name, $age)
	{
		$connection = DBConnection::getDBConnection();
		$sql = "DELETE FROM `user` WHERE name = :NAME and age = :AGE";
		$stmt = $connection->prepare($sql);
		$stmt->bindValue(":NAME", $name, \PDO::PARAM_STR);
		$stmt->bindValue(":AGE", $age, \PDO::PARAM_INT);
		$stmt->execute();
	}
}